package org.lewis.woman.service;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.lang.StringUtils;
import org.lewis.common.domain.Song;
import org.lewis.common.jdbc.QueryHelper;
import org.lewis.common.page.Page;
import org.lewis.common.service.SongService;
import org.lewis.common.service.TagService;

import com.tocersoft.framework.core.annotations.Component;
import com.tocersoft.framework.core.annotations.Injection;

@Component
public class SongServiceImpl implements SongService {

	public static final String ADDSONG = "insert into ts_song (name,file,sdesc,tags,createTime,uid,nickName) values (?,?,?,?,?,?,?)";

	@Injection
	private TagService tagService;
	
	public long addSong(Song song) {
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = QueryHelper.getConnection().prepareStatement(ADDSONG,
					PreparedStatement.RETURN_GENERATED_KEYS);
			ps.setObject(1, song.getName());
			ps.setObject(2, song.getFile());
			ps.setObject(3, song.getSdesc());
			ps.setObject(4, song.getTags());
			ps.setObject(5, song.getCreateTime());
			ps.setObject(6, song.getUid());
			ps.setObject(7, song.getNickName());
			ps.executeUpdate();
			rs = ps.getGeneratedKeys();
			//更新标签的歌曲数量
			if(StringUtils.isNotEmpty(song.getTags())){
				String[] tagsName=song.getTags().split(",");
				tagService.updateTagSongs(tagsName);
			}
			return rs.next() ? rs.getLong(1) : -1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.closeQuietly(rs);
			DbUtils.closeQuietly(ps);
		}
		return 0;
	}

	//@Cacheable(key={"SongSearchByTag","#1","#2.page"},condition={"#2.page.totalCount>0"},refreshPeriod=60*60)
	public Page<Song> querySongByTag(String tagName,Page<Song> page) {
		String sql="select id,name,sdesc,file,listening,uid,nickName from ts_song where tags like ? order by listening desc ";
		String countSql="select count(1) from ts_song where tags like ? ";
		List<Song> result=QueryHelper.queryPage(Song.class, sql, page.getPage(), page.getCount(), "%"+tagName+"%");
		page.setResult(result);
		page.setTotalCount(QueryHelper.count(countSql, "%"+tagName+"%"));
		return page;
	}

	public void updateSongListening(long id) {
		String sql="update ts_song set listening=listening+1 where id=?";
		QueryHelper.update(sql, id);
	}


}
